<template>
  <div class="coordinate-overlay-container">
    <div class="image-container" ref="imageContainer">
      <img 
        :src="imageUrl" 
        :alt="imageName"
        @load="onImageLoad"
        @error="onImageError"
        class="device-image"
      />
      
      <!-- 坐标框覆盖层 -->
      <div 
        v-for="area in scaledClickableAreas" 
        :key="area.id"
        class="clickable-area"
        :style="{
          left: area.x + 'px',
          top: area.y + 'px',
          width: area.width + 'px',
          height: area.height + 'px'
        }"
        @click="handleAreaClick(area)"
        @mouseenter="showTooltip(area, $event)"
        @mouseleave="hideTooltip"
      >
        <div class="area-label">{{ area.label }}</div>
      </div>
    </div>

    <!-- 工具提示 -->
    <div 
      v-if="tooltip.visible"
      class="tooltip"
      :style="{
        left: tooltip.x + 'px',
        top: tooltip.y + 'px'
      }"
    >
      <div class="tooltip-content">
        <div class="tooltip-title">{{ tooltip.area?.label }}</div>
        <div class="tooltip-description">{{ tooltip.area?.description || '点击执行操作' }}</div>
        <div class="tooltip-action">动作: {{ tooltip.area?.action }}</div>
      </div>
    </div>

    <!-- 坐标信息面板 -->
    <div v-if="showCoordinateInfo" class="coordinate-info-panel">
      <div class="panel-header">
        <h4>坐标信息</h4>
        <el-button size="small" @click="toggleCoordinateInfo">
          {{ showCoordinateInfo ? '隐藏' : '显示' }}
        </el-button>
      </div>
      <div class="coordinate-list">
        <div 
          v-for="area in clickableAreas" 
          :key="area.id"
          class="coordinate-item"
          :class="{ active: selectedArea?.id === area.id }"
          @click="selectArea(area)"
        >
          <div class="area-info">
            <span class="area-name">{{ area.label }}</span>
            <span class="area-coords">
              ({{ area.x }}, {{ area.y }}) - {{ area.width }}x{{ area.height }}
            </span>
          </div>
          <div class="area-actions">
            <el-button size="small" type="primary" @click.stop="editArea(area)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click.stop="deleteArea(area)">
              删除
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="panel-actions">
        <el-button type="primary" @click="addNewArea">
          <el-icon><Plus /></el-icon>
          添加区域
        </el-button>
        <el-button @click="exportCoordinates">
          <el-icon><Download /></el-icon>
          导出坐标
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * 坐标覆盖层组件
 * 
 * 功能：
 * - 在设备图片上显示可点击区域
 * - 支持坐标文件解析和显示
 * - 提供坐标编辑和管理功能
 * - 响应式缩放适配不同屏幕尺寸
 */

import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

console.log('CoordinateOverlay组件加载')

// Props定义
const props = defineProps({
  imageUrl: {
    type: String,
    required: true
  },
  imageName: {
    type: String,
    default: '设备图片'
  },
  clickableAreas: {
    type: Array,
    default: () => []
  },
  coordinateFile: {
    type: Object,
    default: null
  },
  editable: {
    type: Boolean,
    default: false
  }
})

// Emits定义
const emit = defineEmits([
  'area-click',
  'coordinates-updated',
  'image-loaded',
  'image-error'
])

// 响应式数据
const imageContainer = ref(null)
const imageLoaded = ref(false)
const imageScale = ref(1)
const originalImageSize = ref({ width: 0, height: 0 })
const containerSize = ref({ width: 0, height: 0 })
const showCoordinateInfo = ref(false)
const selectedArea = ref(null)

// 工具提示相关
const tooltip = ref({
  visible: false,
  x: 0,
  y: 0,
  area: null
})

// 计算属性 - 缩放后的坐标区域
const scaledClickableAreas = computed(() => {
  if (!imageLoaded.value || !props.clickableAreas.length) {
    return []
  }
  
  return props.clickableAreas.map(area => ({
    ...area,
    x: Math.round(area.x * imageScale.value),
    y: Math.round(area.y * imageScale.value),
    width: Math.round(area.width * imageScale.value),
    height: Math.round(area.height * imageScale.value)
  }))
})

// 方法定义
const onImageLoad = (event) => {
  console.log('图片加载完成')
  imageLoaded.value = true
  originalImageSize.value = {
    width: event.target.naturalWidth,
    height: event.target.naturalHeight
  }
  
  nextTick(() => {
    calculateScale()
    emit('image-loaded', {
      originalSize: originalImageSize.value,
      scale: imageScale.value
    })
  })
}

const onImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  ElMessage.error('图片加载失败')
  emit('image-error', event.target.src)
}

const calculateScale = () => {
  if (!imageContainer.value || !imageLoaded.value) return
  
  const container = imageContainer.value
  const containerRect = container.getBoundingClientRect()
  const img = container.querySelector('.device-image')
  
  if (!img) return
  
  const imgRect = img.getBoundingClientRect()
  
  containerSize.value = {
    width: containerRect.width,
    height: containerRect.height
  }
  
  // 计算缩放比例
  const scaleX = imgRect.width / originalImageSize.value.width
  const scaleY = imgRect.height / originalImageSize.value.height
  imageScale.value = Math.min(scaleX, scaleY)
  
  console.log('图片缩放比例:', imageScale.value)
}

const handleAreaClick = (area) => {
  console.log('点击坐标区域:', area.label)
  selectedArea.value = area
  emit('area-click', area)
}

const showTooltip = (area, event) => {
  if (!props.editable) return
  
  tooltip.value = {
    visible: true,
    x: event.clientX + 10,
    y: event.clientY - 10,
    area
  }
}

const hideTooltip = () => {
  tooltip.value.visible = false
}

const toggleCoordinateInfo = () => {
  showCoordinateInfo.value = !showCoordinateInfo.value
}

const selectArea = (area) => {
  selectedArea.value = area
  console.log('选择坐标区域:', area.label)
}

const editArea = (area) => {
  console.log('编辑坐标区域:', area.label)
  // TODO: 实现坐标区域编辑功能
  ElMessage.info('坐标编辑功能开发中')
}

const deleteArea = (area) => {
  console.log('删除坐标区域:', area.label)
  // TODO: 实现坐标区域删除功能
  ElMessage.info('坐标删除功能开发中')
}

const addNewArea = () => {
  console.log('添加新坐标区域')
  // TODO: 实现添加新坐标区域功能
  ElMessage.info('添加坐标区域功能开发中')
}

const exportCoordinates = () => {
  console.log('导出坐标数据')
  const coordinateData = {
    imageInfo: {
      name: props.imageName,
      url: props.imageUrl,
      originalSize: originalImageSize.value
    },
    clickableAreas: props.clickableAreas,
    exportTime: new Date().toISOString()
  }
  
  const dataStr = JSON.stringify(coordinateData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = `${props.imageName}_coordinates.json`
  link.click()
  
  URL.revokeObjectURL(url)
  ElMessage.success('坐标数据导出成功')
}

// 监听窗口大小变化
const handleResize = () => {
  if (imageLoaded.value) {
    calculateScale()
  }
}

// 生命周期
watch(() => props.imageUrl, () => {
  imageLoaded.value = false
  selectedArea.value = null
})

watch(() => props.editable, (newVal) => {
  showCoordinateInfo.value = newVal
})

// 暴露方法给父组件
defineExpose({
  calculateScale,
  exportCoordinates,
  toggleCoordinateInfo
})
</script>

<style scoped>
.coordinate-overlay-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.image-container {
  position: relative;
  width: 100%;
  height: auto;
  display: inline-block;
}

.device-image {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
}

.clickable-area {
  position: absolute;
  border: 2px solid #3b82f6;
  background-color: rgba(59, 130, 246, 0.1);
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clickable-area:hover {
  border-color: #1d4ed8;
  background-color: rgba(29, 78, 216, 0.2);
  box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
}

.area-label {
  background: rgba(59, 130, 246, 0.9);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  pointer-events: none;
}

.tooltip {
  position: fixed;
  z-index: 1000;
  pointer-events: none;
}

.tooltip-content {
  background: #1f2937;
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  max-width: 200px;
}

.tooltip-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.tooltip-description {
  color: #d1d5db;
  margin-bottom: 4px;
}

.tooltip-action {
  color: #60a5fa;
  font-weight: 500;
}

.coordinate-info-panel {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 300px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
}

.panel-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #111827;
}

.coordinate-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
}

.coordinate-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.coordinate-item:hover {
  background-color: #f3f4f6;
}

.coordinate-item.active {
  background-color: #dbeafe;
  border: 1px solid #3b82f6;
}

.area-info {
  flex: 1;
}

.area-name {
  display: block;
  font-weight: 500;
  color: #111827;
  font-size: 13px;
}

.area-coords {
  display: block;
  color: #6b7280;
  font-size: 11px;
  margin-top: 2px;
}

.area-actions {
  display: flex;
  gap: 4px;
}

.panel-actions {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  gap: 8px;
}

.panel-actions .el-button {
  flex: 1;
}
</style>
